﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace AppEntity
{
    public partial class Common
    {
        public partial class XslExtensionObject
        {
            private Dictionary<string, string> _Variable = new Dictionary<string, string>();

            public string Variable(string name, string value)
            {
                if (this._Variable.ContainsKey(name))
                {
                    this._Variable[name] = value;
                }
                else
                {
                    this._Variable.Add(name, value);
                }
                return "";
            }

            public string Variable(string name)
            {
                return this._Variable[name];
            }

            public string GUID()
            {
                return Utility.GUID();
            }

            public string MD5(string str)
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToUpper();
            }

            public string MD5Lower(string str)
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
            }

            public string SecureUri(string str)
            {
                return Regex.Replace(str, @"\W", "", RegexOptions.IgnoreCase);
            }

            public static string SecureString(string str)
            {
                
                return new AppEntity.Common.XslExtensionObject().SecureUri(str);
            }

            public string GetNowTime()
            {
                return Utility.GetNowTime();
            }

            public string FormatDateTime(string dt, string format)
            {
                DateTime d;
                if (string.IsNullOrEmpty(dt) || !DateTime.TryParse(dt, out d)) return "";

                return d.ToString(format);
            }

            public string FormatDateTimeByCulture(string dt, string format, string lang)
            {
                DateTime d;
                if (string.IsNullOrEmpty(dt) || !DateTime.TryParse(dt, out d)) return "";
                return d.ToString(format, new System.Globalization.CultureInfo(lang));
            }

            public string FormatDateTime(string dt, string format, string timezone)
            {
                return Utility.GetDateTimeByString(dt, timezone).ToString(format);
            }

            public string FormatDateTimeByCultureInfo(string dt, string format, string lang)
            {
                return Utility.GetDateTimeByString(dt).ToString(format, new System.Globalization.CultureInfo(lang));
            }

            public string GetTimeStamp()
            {
                return Utility.GetTimeStamp();
            }

            public string UrlDomain()
            {
                return HttpContext.Current.Request.Url.DnsSafeHost;
            }

            public string UrlHost()
            {
                return HttpContext.Current.Request.Url.Host;
            }

            public string UrlProcotol()
            {
                return HttpContext.Current.Request.Url.Scheme;
            }

            public string UrlQuery()
            {
                return HttpContext.Current.Request.Url.Query;
            }

            public string DateTimeAddDate(string dt, double n)
            {
                return Utility.GetDateTimeByString(dt).AddDays(n).ToString("yyyy-MM-ddTHH:mm:ss.fffK");
            }

            public string DateTimeDiff(string date1, string date2)
            {
                DateTime dt1 = Utility.GetDateTimeByString(date1);
                DateTime dt2 = Utility.GetDateTimeByString(date2);
                TimeSpan ts = dt1 - dt2;
                string duration = ts.Days + "天" + ts.Hours % 24 + "小时" + ts.Minutes + "分";
                return duration;
            }

            public string DateTimeDiffToSeconds(string date1, string date2)
            {
                DateTime dt1 = Utility.GetDateTimeByString(date1);
                DateTime dt2 = Utility.GetDateTimeByString(date2);
                TimeSpan ts = dt1 - dt2;
                return ts.TotalSeconds.ToString();
            }

            public string StripAllHtmlTag(string html)
            {
                string txt = Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
                return Regex.Replace(txt, @"&.*?;", "").NormalizeWhiteSpace();
            }

            public string RegexReplace(string str, string regex, string target)
            {
                return Regex.Replace(str, regex, target);
            }

            public string RegexReplace(string str, string regex, string target, string opt)
            {
                if (string.IsNullOrEmpty(opt) || opt.ToLower() != "i")
                {
                    return RegexReplace(str, regex, target);
                }
                return Regex.Replace(str, regex, target, RegexOptions.IgnoreCase);
            }

            public string RegexMatch(string str, string regex, string splitchar)
            {
                Regex Reg = new Regex(regex, RegexOptions.IgnoreCase);
                // 搜索匹配的字符串
                MatchCollection matches = Reg.Matches(str);

                string[] Result = new string[matches.Count];
                int i = 0;
                foreach (Match match in matches)
                {
                    Result[i++] = match.Groups[0].Value;
                }
                return Result.Join(splitchar);
            }

            public string Trim(string str)
            {
                return str.Trim();
            }

            public string Format(string data, string type, string param)
            {
                switch (type.ToLower())
                {
                    case "datetime":
                        {
                            return FormatDateTime(data, param);
                        }
                        break;
                }
                return data;
            }

            public string Substring(string str, int begin, int end)
            {
                if (begin < 0)
                {
                    begin = 0;
                }
                if (end > str.Length - 1)
                {
                    end = str.Length - 1;
                }
                return str.Substring(begin, end);
            }

            public string Substring(string str, int begin)
            {
                if (begin < 0)
                {
                    begin = 0;
                }
                return str.Substring(begin);
            }

            public int IndexOf(string str, string str2)
            {
                return str.IndexOf(str2);
            }

            public int LastIndexOf(string str, string str2)
            {
                return str.LastIndexOf(str2);
            }

            public string ToLower(string str)
            {
                return str.ToLower();
            }

            public string ToUpper(string str)
            {
                return str.ToUpper();
            }

            public string Contain(string str, string str2)
            {
                return str.Contains(str2) ? "1" : "0";
            }

            public string Replace(string str, string str2, string str3)
            {
                return str.Replace(str2, str3);
            }

            public string StartsWith(string str, string str2)
            {
                return str.StartsWith(str2, true, null) == true ? "1" : "0";
            }

            public string EndsWith(string str, string str2)
            {
                return str.EndsWith(str2, true, null) == true ? "1" : "0";
            }

            public string UrlEncode(string url)
            {
                return HttpUtility.UrlEncode(url);
            }

            public string UrlEncode(string url, string encoder)
            {
                return HttpUtility.UrlEncode(url, encoder.ToUpper() == "ASCII" ? Encoding.ASCII : Encoding.UTF8);
            }

            public string UrlDecode(string Url)
            {
                return HttpUtility.UrlDecode(Url);
            }

            public string ToLowerCase(string str)
            {
                return str.ToLower();
            }

            public string ToUpperCase(string str)
            {
                return str.ToUpper();
            }

            //public string ExecXPath(string xmluri, string xpath, string value)
            //{
            //    if (string.IsNullOrEmpty(xmluri))
            //        return "";
            //    if (xmluri.Substring(0, 1) == "/")
            //    {
            //        xmluri = xmluri.Replace("/", "\\");
            //    }
            //    if (xmluri.Substring(0, 1) == "\\")
            //    {
            //        string xmlpath = SBS.Base.GlobalCache.GetSiteConfig().SelectSingleNode("/root/app").InnerText + xmluri.Substring(1);

            //        XmlDocument dom = new XmlDocument();
            //        dom.Load(xmlpath);
            //        if (!string.IsNullOrEmpty(value))
            //        {
            //            xpath = xpath.Replace("{THIS.VALUE}", value);
            //        }
            //        XmlNode n = dom.SelectSingleNode(xpath);
            //        if (n == null)
            //        {
            //            return "";
            //        }
            //        else
            //        {
            //            return n.Value;
            //        }

            //    }
            //    return "done";
            //}

            //public string ExecXPath(string xmluri, string xpath)
            //{
            //    return ExecXPath(xmluri, xpath, null);
            //}

            public XPathNavigator ImportXmlDoc(string xmlfile)
            {
                if (xmlfile.Substring(1, 2) != ":\\")
                {
                    xmlfile = HttpContext.Current.Server.MapPath(xmlfile);
                }
                if (!File.Exists(xmlfile))
                {
                    return new XPathDocument(new StringReader("<root/>")).CreateNavigator();
                }
                XPathDocument xdom = new XPathDocument(xmlfile);
                XPathNavigator nav = xdom.CreateNavigator();
                nav.MoveToRoot();
                return nav;
            }

            public XPathNavigator ImportXmlString(string XmlString)
            {
                XmlDocument dom = new XmlDocument();
                dom.LoadXml(XmlString);
                return dom.CreateNavigator();
            }

            public string ImportTextFile(string TextFile)
            {
                if (!File.Exists(TextFile)) return string.Empty;
                return File.ReadAllText(TextFile, Encoding.Default);
            }

            public string GetServerMapPath(string Path)
            {
                return HttpContext.Current.Server.MapPath(Path);
            }

            public string GetServerMapPath()
            {
                return HttpContext.Current.Server.MapPath(".");
            }

            //public XmlDocument GetSiteConfig()
            //{
            //    return SBS.Base.GlobalCache.GetSiteConfig();
            //}

            //public string GetDataRoot()
            //{
            //    return SBS.Base.GlobalCache.GetSiteConfig().SelectSingleNode("/root/xmldata").InnerText;
            //}

            public string GetCookie(string name)
            {
                HttpCookie coo = HttpContext.Current.Request.Cookies[name];
                if (coo == null)
                {
                    return "";
                }
                return coo.Value;
            }

            public string NormalizeWhiteSpace(string Txt)
            {
                return Txt.NormalizeWhiteSpace();
            }
        }
    }
}
